package smartbooksdb.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class ErrorLogger implements CommonConstantsDB {

	public static void log(Throwable ex, boolean sendMail) {

		File file = new File("error.log");
		Map<String, String> mailMap = new HashMap<String, String>();

		try {
			StringWriter sw = new StringWriter();
			ex.printStackTrace(new PrintWriter(sw));

			mailMap.put(MAIL_FROM, "mail@vpack.co.in");
			mailMap.put(MAIL_TO1, "dedhia88@gmail.com");
			mailMap.put(MAIL_TO2, "ankit_jain@live.in");
			mailMap.put(MAIL_USERNAME, "mail@vpack.co.in");
			mailMap.put(MAIL_PASSWORD, "vpack@1234");
			mailMap.put(MAIL_SUBJECT, "SmartBoooks Error Log");
			mailMap.put(MAIL_BODY, sw.toString());
			mailMap.put(MAIL_HOST, "mail.vpack.co.in");
			mailMap.put(MAIL_PORT, "25");
			mailMap.put(MAIL_DISPLAY_NAME, "SmartBooks Mailer");

			FileOutputStream outputStream = new FileOutputStream(file, true);
			PrintStream printStream = new PrintStream(outputStream);
			ex.printStackTrace(printStream);
			outputStream.flush();
			outputStream.close();

			if (sendMail) {
				SendMail mail = new SendMail();
				mail.send(mailMap);
			}
		} catch (FileNotFoundException e) {
			ErrorLogger.mail(mailMap);
		} catch (IOException e) {
			ErrorLogger.mail(mailMap);
		}
	}

	public static void mail(Map<String, String> mailMap) {
		SendMail mail = new SendMail();
		mail.send(mailMap);
	}
}
